from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from rest_framework.filters import OrderingFilter, SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
from utils.APIResponse import APIResponse
from .models import CourseCategory, Course, CourseChapter
from .serializer import CourseCategorySerializer, CourseSerializer, CourseChapterSerializer
from .pagination import CommonPageNumberPagination


# 课程分类接口
class CourseCategoryView(GenericViewSet, ListModelMixin):
    queryset = CourseCategory.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseCategorySerializer

    def list(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        return APIResponse(data=res.data)


# 课程列表接口
class CourseView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = Course.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseSerializer
    # 加入分页
    pagination_class = CommonPageNumberPagination
    # 加入排序  过滤 按课程分类过滤 django-filter
    filter_backends = [OrderingFilter, DjangoFilterBackend, ]
    ordering_fields = ['price', 'students']
    filter_fields = ['course_category']

    def list(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        return APIResponse(data=res.data)


# 课程章节接口
class CourseChapterView(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = CourseChapter.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseChapterSerializer
    filter_backends = [DjangoFilterBackend, ]
    # 按照课程id过滤
    filter_fields = ['course_id']


# 针对实战课的搜索接口
class CourseSearchView(GenericViewSet, ListModelMixin):
    queryset = Course.objects.all().filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseSerializer
    pagination_class = CommonPageNumberPagination
    filter_backends = [SearchFilter]
    search_fields = ['name', ]

    # def list(self, request, *args, **kwargs):
    #     # 这个查的是实战课
    #     res=super().list(request, *args, **kwargs)
    #     # res2=查询免费课
    #     # res3=查询轻课
    #     # 上面全是取数据库查询
    #     # 后期改成取es中查询，
    #     return APIResponse(result={'free_course':'字典','actual_course':res.data})
